package com.activity.common.aop;

import com.activity.entity.Aclog;
import com.activity.service.impl.AclogServiceImpl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

//自定义注解
@Aspect
@Component
public class OperLogAspect {
    @Pointcut("@annotation(com.activity.common.aop.OperLog)")
    public void operLogPoinCut() {
    }

    @Resource
    private AclogServiceImpl logService;


    @AfterReturning(value = "operLogPoinCut()", returning="returnValue")
    public void saveOperLog(JoinPoint joinPoint, Object returnValue) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperLog opLog = method.getAnnotation(OperLog.class);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        String username = (String)request.getSession().getAttribute("username");
        Date date=new Date();
        String logdate = date.toString();

        Aclog log = new Aclog();
        log.setName(username);
        log.setModul(opLog.operModul());
        log.setType(opLog.operType());
        log.setDetail(opLog.operDesc());
        log.setDate(logdate);
        logService.insertLog(log);
    }
}
